package com.learning.springboot.webSocket.Controller;

import com.learning.springboot.webSocket.entity.Message;
import com.learning.springboot.webSocket.entity.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.security.Principal;

/**
 * Created by td on 2017/9/13.
 */
@Controller
public class WsController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public MessageResponse say(Message message)throws Exception{
       // Thread.sleep(3000);
        return new MessageResponse().setResponseMessage("Welcom, "+message.getName()+"!");
    }

    @GetMapping("/ws")
    public String view(){
        return "ws";
    }

    @MessageMapping("/chat")
    public void  handleChat(Principal principal,String msg) {
        if (principal.getName().equals("zhangsan")){
            simpMessagingTemplate.convertAndSendToUser("lisi","/queue/notifications",
                    principal.getName()+"---Send:"+msg);
        }else if (principal.getName().equals("lisi")){
            System.out.println("李四的消息:"+msg);
            System.out.println(principal.getName());
            simpMessagingTemplate.convertAndSendToUser("zhangsan","/queue/notifications",
                    principal.getName()+"---Send:"+msg);
        }
    }

}
